package com.voodoo.lib_http.callback;

import com.voodoo.lib_http.utils.OkHttpUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Author: voodoo
 * CreateDate: 2021/05/29
 * Description:
 */
public class FileCallBack extends Callback<File> {

    private String destFileDir; // 目标文件存储的文件夹路径
    private String destFileName; // 目标文件存储的文件名

    public FileCallBack(String destFileDir, String destFileName) {
        this.destFileDir = destFileDir;
        this.destFileName = destFileName;
    }

    @Override
    public File parseNetworkResponse(Response response, int id) throws Exception {
        return saveFile(response, id);
    }

    public File saveFile(Response response, final int id) throws IOException {
        InputStream inputStream = null;
        byte[] buf = new byte[2048];
        int len = 0;
        FileOutputStream outputStream = null;

        try {
            inputStream = response.body().byteStream();
            final long total = response.body().contentLength();

            long sum = 0;

            File dir = new File(destFileDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            File file = new File(dir, destFileName);
            outputStream = new FileOutputStream(file);
            while ((len = inputStream.read(buf)) != -1) {
                sum += len;
                outputStream.write(buf, 0, len);
                final long finalSum = sum;
                OkHttpUtils.getInstance().getDelivery().execute(new Runnable() {
                    @Override
                    public void run() {
                        onRequesting(finalSum, total, id);
                    }
                });
            }
            outputStream.flush();
            return file;
        } finally {
            try {
                response.body().close();
                if (inputStream != null) {
                    inputStream.close();
                }

                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
            }
        }
    }

    @Override
    public void onError(Call call, Exception exception, int id) {

    }

    @Override
    public void onResponse(File response, int id) {

    }

}
